Find Roots of Quadratic Equation

Theory:

A quadratic equation is of the form ax^2 + bx + c = 0, where a, b, and c are constants. The roots of a quadratic equation can be calculated using the quadratic formula: (-b ± √(b^2 - 4ac)) / (2a).

Python Code:

import math

def find_roots(a, b, c):
    discriminant = b ** 2 - 4 * a * c
    if discriminant > 0:
        root1 = (-b + math.sqrt(discriminant)) / (2 * a)
        root2 = (-b - math.sqrt(discriminant)) / (2 * a)
        return root1, root2
    elif discriminant == 0:
        root = -b / (2 * a)
        return root, root
    else:
        real_part = -b / (2 * a)
        imaginary_part = math.sqrt(abs(discriminant)) / (2 * a)
        root1 = complex(real_part, imaginary_part)
        root2 = complex(real_part, -imaginary_part)
        return root1, root2

# Taking input for the coefficients of the quadratic equation and calculating its roots
def calculate_and_display_roots():
    a = float(input("Enter the coefficient a: "))
    b = float(input("Enter the coefficient b: "))
    c = float(input("Enter the coefficient c: "))
    roots = find_roots(a, b, c)
    print("Roots of the quadratic equation:", roots)

calculate_and_display_roots()

Example Output 1:

Enter the coefficient a: 1

Enter the coefficient b: -3

Enter the coefficient c: 2

Roots of the quadratic equation: (2.0, 1.0)

Example Output 2:

Enter the coefficient a: 1

Enter the coefficient b: 2

Enter the coefficient c: 1

Roots of the quadratic equation: (-1.0, -1.0)

Code Explanation:

The function find_roots(a, b, c) calculates the roots of a quadratic equation using the quadratic formula.

The function calculate_and_display_roots() takes input for the coefficients of the quadratic equation, calculates its roots using the aforementioned function, and displays the result.